// 客服的id
var kf_id = 0;
var kf_name = '';
// 是否点击显示表情的标志
var flag = 1;
// 是否点击显示收藏的标志
var flag2 = 1;
// 发送锁  标识
var sendLock = 0;
// 是否显示默认的聊天记录
var commChat = 1;
// 客服状态
var kfStatus = 0;
// 连接服务器
if (config != undefined && config.socket != undefined) {

  // 创建一个Socket实例
  var socket = new ReconnectingWebSocket('ws://' + config.socket);

  // 加锁
  // lockInput();
  //showSystem({content: '连接中...'});
  document.getElementById('title').innerText = '连接中,若长时间无响应请刷新页面';

  // 打开Socket
  socket.onopen = function (res) {
    console.log('握手成功');
    console.log(3333)
    // 登录
    // var goodsCommonId = window.localStorage.getItem('currentgoodscommonid') || ''
    var login_data = '{"type":"userInit", "uid": ' + config.uid + ', "name" : "' + config.name +
      '", "avatar" : "' + config.avatar + '", "group" : ' + config.group + ', "goods_commonid": "' + config.goods_commonid + '"}';
    socket.send(login_data);
    if (1 == commChat) {
      // showChatLog();
      getChatLog(config.uid, 0, 1)
    }
    // 解锁
    // unlockInput();
  };

  // 监听消息
  socket.onmessage = function (res) {
    var data = eval("(" + res.data + ")");
    switch (data['message_type']) {
      // 服务端ping客户端
      case 'ping':
        socket.send('{"type":"ping"}');
        break;
      // 已经被分配了客服
      case 'connect':
        kfStatus = 1;
        kf_id = data.data.kf_id;
        kf_name = data.data.kf_name;
        showSystem({content: '客服 ' + data.data.kf_name + ' 为您服务'});
        document.getElementById('title').innerHTML = '与 ' + kf_name + ' 交流中';
        unlockInput();
        break;
      // 排队等待
      case 'wait':
        kfStatus = 2;
        unlockInput();
        // lockInput();
        document.getElementById('title').innerHTML = '请稍后再来';
        showMsg(data.data);
        break;
      // 监测聊天数据
      case 'chatMessage':
        showMsg(data.data);
        break;
      // 问候语
      case 'helloMessage':
        showMsg(data.data, 1);
        break;
      // 转接
      case 'relinkMessage':
        commChat = 2;
        document.getElementById('title').innerHTML = '正在转接中...';
        break;
    }
  };
  // 监听错误
  socket.onerror = function (err) {
    showSystem({content: '连接失败'});
    document.getElementById('title').innerText = '连接失败';
  };
}

// 图片 文件上传
layui.use(['upload', 'layer'], function () {
  var layer = layui.layer;
  var url = config.chatSite + '/index/upload/uploadImg'
  var upload = layui.upload;
  // 执行实例
  var uploadInstImg = upload.render({
    elem: '#up-image' // 绑定元素
    , accept: 'images'
    , exts: 'jpg|jpeg|png|gif'
    // , multiple: 'true'
    , url: url // 上传接口
    , before: function () {
      layer.load()
    }
    , done: function (res) {
      layer.closeAll('loading');
      console.log('img', res.data.src)
      sendMsg('img[' + res.data.src + ']');
    }
    , error: function () {
      layer.closeAll('loading');
      // 请求异常回调
    }
  });
  var url2 = config.chatSite + '/index/upload/uploadVideo'

  var uploadInstVideo = upload.render({
    elem: '#up-video' // 绑定元素
    , accept: 'video'
    , exts: 'mp4'
    , size: '10240'
    , url: url2 // 上传接口
    , before: function () {
      layer.load()
    }
    , done: function (res) {
      layer.closeAll('loading');
      sendMsg('video[' + res.data.src + ']');
    }
    , error: function () {
      layer.closeAll('loading');
      // 请求异常回调
    }
  });

  $('.layui-upload-file').hide();
});

// layui.use(['upload'], function () {
//   var upload = layui.upload;
//
//   var uploadInstImg = upload.render({
//     elem: '#up-image'
//     , accept: 'images'
//     , exts: 'jpg|jpeg|png|gif'
//     , url: '/index/upload/uploadImg'
//     , done: function (res) {
//
//       sendMsg('img[' + res.data.src + ']');
//     }
//     , error: function () {
//     }
//   });
//
//   $('.layui-upload-file').hide();
// });

$(function () {

  // 监听输入改变发送按钮
  $("#msg").bind('input porpertychange', function () {

    if ($("#msg").val().length > 0) {
      $(".layim-send").removeClass('layui-disabled');
    } else {
      $(".layim-send").addClass('layui-disabled');
    }
  });

  // 点击发送
  $("#send").click(function () {
    sendMsg();
  });

  // 点击表情
  $('#up-face').click(function (e) {
    e.stopPropagation();
    if (1 == flag) {
      showFaces();
      $('#face-box').show();
      flag = 2;
    } else {
      $('#face-box').hide();
      flag = 1;
    }
  });

// 点击我的收藏
  $('#up-favorite').click(function (e) {
    e.stopPropagation();
    if (1 == flag2) {
      showFavorite();
      $('#favorite-box').show();
      flag2 = 2;
    } else {
      $('#favorite-box').hide();
      flag2 = 1;
    }
  });
  // 监听点击旁边关闭表情
  document.addEventListener("click", function () {
    if (2 == flag) {
      document.getElementById('face-box').style.display = 'none';
      flag = 1;
    }
    if (2 == flag2) {
      document.getElementById('favorite-box').style.display = 'none';
      flag2 = 1;
    }
  });
});

// 发送消息
function sendMsg(sendMsg) {

  if (1 == sendLock) {
    return false;
  }

  var msg = (typeof(sendMsg) == 'undefined') ? $('#msg').val() : sendMsg;
  if ('' == msg) {
    return false;
  }

  var _html = $("#chat-list").html();
  var time = getTime();
  var content = replaceContent(msg);

  _html += '<li class="layim-chat-system"><span>' + time + '</span></li>'
  _html += '<li class="layim-chat-li layim-chat-mine">';
  _html += '<div class="layim-chat-user">';
  _html += '<img src="' + config.avatar + '"><cite>我</cite></div>';
  _html += '<div class="layim-chat-text">' + content + ' </div></li>';

  $('#chat-list').html(_html);
  var chatType = 'chatMessage'
  if (kfStatus == 2 || kfStatus == 0) {
    chatType = 'waitKf'
  }
  // 发送消息
  socket.send(JSON.stringify({
    type: chatType,
    data: {
      to_id: kf_id, to_name: kf_name, content: msg, from_name: config.name,
      from_id: config.uid, from_avatar: config.avatar
    }
  }));

  // 储存我发出的信息
  var key = kf_id + '-' + config.uid;
  if (typeof(Storage) !== "undefined") {
    var localMsg = getCache(key);
    if (localMsg == null || localMsg.length == 0) {
      localMsg = [];
    }
    localMsg.push({type: 'mine', name: '我', time: time, content: content, avatar: config.avatar});

    cacheChat({key: key, data: localMsg});
  }

  $('#msg').val('');
  $(".layim-send").addClass('layui-disabled');

  // 滚动条自动定位到最底端
  wordBottom();
}

// 展示发送来的消息
function showMsg(info, flag) {
  console.log('info', info)
  var _html = $("#chat-list").html();
  var content = replaceContent(info.content);

  _html += '<li class="layim-chat-system"><span>' + info.time + '</span></li>';
  _html += '<li class="layim-chat-li">';
  _html += '<div class="layim-chat-user">';
  _html += '<img src="' + info.avatar + '"><cite>' + info.name + '</cite></div>';
  if (info.extend_data) {
    _html += '<div class="layim-chat-text">'
    info.extend_data.image = info.extend_data.image || (config.shopSite + '/wapnew1/static/images/coupon.jpg')
    _html += '<img class="layui-whisper-photos" style="float: left" src="' + info.extend_data.image + '" width="80px" height="80px">'
    _html += '<p style="float: left; margin: 20px 5px;" onclick="gotoDetail(\'' + info.extend_data.id + '\',\'' + info.extend_data.type + '\')">' + info.extend_data.name + '</p>'
    _html += '</div></li>';
  } else {
    _html += '<div class="layim-chat-text">' + content + '</div></li>';
  }
  $('#chat-list').html(_html);

  // 滚动条自动定位到最底端
  wordBottom();

  // 储存我收到的信息
  var key = kf_id + '-' + config.uid;
  if (typeof(Storage) !== "undefined" && typeof(flag) == "undefined") {
    var localMsg = getCache(key);
    if (localMsg == null || localMsg.length == 0) {
      localMsg = [];
    }
    localMsg.push({type: 'other', name: info.name, time: info.time, content: content, avatar: info.avatar});

    cacheChat({key: key, data: localMsg});
  }
}

// 获取时间
function getTime() {
  var myDate = new Date();
  var hour = myDate.getHours();
  var minute = myDate.getMinutes();
  if (hour < 10) hour = '0' + hour;
  if (minute < 10) minute = '0' + minute;

  return hour + ':' + minute;
}

// 缓存聊天数据 [本地存储策略]
function cacheChat(obj) {
  if (typeof(Storage) !== "undefined") {
    localStorage.setItem(obj.key, JSON.stringify(obj.data));
  }
}

// 从本地缓存中，拿出数据
function getCache(key) {
  return JSON.parse(localStorage.getItem(key));
}

// 对话框定位到最底端
function wordBottom() {
  // 滚动条自动定位到最底端
  var box = $(".layim-chat-main");
  box.scrollTop(box[0].scrollHeight);
}

// 锁住输入框
function lockInput() {
  sendLock = 1;
  document.getElementById('msg').setAttribute('readonly', 'readonly');
}

// 解锁输入框
function unlockInput() {
  sendLock = 0;
  document.getElementById('msg').removeAttribute('readonly');
}

// 展示表情数据
function showFaces() {
  var alt = getFacesIcon();
  var _html = '<ul class="layui-layim-face">';
  var len = alt.length;
  for (var index = 0; index < len; index++) {
    _html += '<li title="' + alt[index] + '" onclick="checkFace(this)"><img src="static/customer/images/face/' + index + '.gif" /></li>';
  }
  _html += '</ul>';

  document.getElementById('face-box').innerHTML = _html;
}

// 展示收藏的图片
var page = 1
var loadedPage = 0
var nextPage = 2
var key = window.localStorage.getItem('key')

function showFavorite() {
  page = 1
  $('#favorite-box-ul').html('')
  getFavoriteImgList(page)
}

function getFavoriteImgList(page) {
  layer.load()
  $.post(config.chatSite + '/index/Favorite/getFavoriteList', {key: key, page: page}, function (response) {
    layer.closeAll('loading');
    loadedPage = page
    // var _html = '<ul class="layui-layim-face">';
    var _html = ''
    if (response.data.length > 0) {
      for (var index = 0; index < response.data.length; index++) {
        _html += '<li style="width: auto" title="' + response.data[index].f_content + '" onclick="checkFavorite(this)"><img style="width: 50px; height: 50px;" src="' + config.chatSite + response.data[index].f_content + '" /></li>';
      }
    } else {
      _html += '<li style="width: 100%; font-size: 14px;">无数据~</li>';
    }
    if (response.data.length >= 12) { // 接口每页12条
      _html += '<li style="width: 100%; font-size: 14px;"><span onclick="getMoreFavorite(this)" class="layui-icon layim-tool-favorite" title="更多" id="up-favorite">&#xe61a;</span>\n</li>';
    }
    // _html += '</ul>';

    $('#favorite-box-ul').append(_html);
  });
}

function getMoreFavorite(current) {
  cancelBubble()
  getFavoriteImgList(++page)
  $(current).parent().remove()
}

// 选择表情
function checkFace(obj) {
  var msg = document.getElementById('msg').value;
  document.getElementById('msg').value = msg + ' face' + obj.title + ' ';
  document.getElementById('face-box').style.display = 'none';
  $(".layim-send").removeClass('layui-disabled');
  flag = 1;
}

// 选择收藏的图片
function checkFavorite(obj) {
  var msg = document.getElementById('msg').value;
  document.getElementById('msg').value = msg + ' img[' + obj.title + ']';
  document.getElementById('favorite-box').style.display = 'none';
  $(".layim-send").removeClass('layui-disabled');
  flag = 1;
}

// sendMsg('img[' + res.data.src + ']');

// 系统消息
function showSystem(info) {

  $("#chat-list").append('<li class="layim-chat-system"><span>' + info.content + '</span></li>');
}

// 展示本地聊天缓存
function showChatLog() {

  var chatLog = getCache(kf_id + '-' + config.uid);
  if (chatLog == null || chatLog.length == 0) {
    return;
  }

  var _html = '';
  var len = chatLog.length;
  for (var i = 0; i < len; i++) {
    var item = chatLog[i];
    if ('mine' == item.type) {

      _html += '<li class="layim-chat-system"><span>' + item.time + '</span></li>'
      _html += '<li class="layim-chat-li layim-chat-mine">';
      _html += '<div class="layim-chat-user">';
      _html += '<img src="' + item.avatar + '"><cite>' + item.name + '</cite></div>';
      _html += '<div class="layim-chat-text">' + replaceContent(item.content) + ' </div></li>';

    } else if ('other' == item.type) {

      _html += '<li class="layim-chat-system"><span>' + item.time + '</span></li>';
      _html += '<li class="layim-chat-li">';
      _html += '<div class="layim-chat-user">';
      _html += '<img src="' + item.avatar + '"><cite>' + item.name + '</cite></div>';
      _html += '<div class="layim-chat-text">' + replaceContent(item.content) + '</div></li>';
    }
  }

  document.getElementById('chat-list').innerHTML = _html;

  // 滚动条自动定位到最底端

  wordBottom();
}

// 退出
function loginOut() {
  window.history.go(-1);
}

// 获取聊天记录
function getChatLog(uid, kf_id, page) {
  // layer.load()
  let url = config.chatSite + '/index/index/getChatLog'
  $.getJSON(url, {uid: uid, kf_id: kf_id, page: page}, function (res) {
    // layer.closeAll('loading');
    if (1 == res.code && res.data.length > 0) {
      var _html = '';
      var len = res.data.length;
      if (len == 15) {
        _html += '<li class="layim-chat-system"><span style="color: #000; background: none" onclick="getMoreChatLog(this' + ',' + uid + ',' + 'kf_id' + ',' + (page + 1) + ')">点击加载更多...</span></li>'
      } else {
        _html += '<li class="layim-chat-system"><span style="color: #000; background: none">没有更多了</span></li>'
      }
      for (var i = 0; i < len; i++) {
        var item = res.data[len - i - 1];

        if ('mine' == item.type) {

          _html += '<li class="layim-chat-system"><span>' + item.time_line + '</span></li>'
          _html += '<li class="layim-chat-li layim-chat-mine">';
          _html += '<div class="layim-chat-user">';
          _html += '<img src="' + item.from_avatar + '"><cite>' + item.from_name + '</cite></div>';
          // _html += '<div class="layim-chat-text">' + replaceContent(item.content) + ' </div></li>';

        } else if ('user' == item.type) {

          _html += '<li class="layim-chat-system"><span>' + item.time_line + '</span></li>';
          _html += '<li class="layim-chat-li">';
          _html += '<div class="layim-chat-user">';
          _html += '<img src="' + item.from_avatar + '"><cite>' + item.from_name + '</cite></div>';
          // _html += '<div class="layim-chat-text">' + replaceContent(item.content) + '</div></li>';
        }
        if (item.extend_data) {
          _html += '<div class="layim-chat-text">'
          item.extend_data.image = item.extend_data.image || (config.shopSite + '/wapnew1/static/images/coupon.jpg')
          _html += '<img class="layui-whisper-photos" style="float: left" src="' + item.extend_data.image + '" width="80px" height="80px">'
          _html += '<p style="float: left; margin: 20px 5px;" onclick="gotoDetail(\'' + item.extend_data.id + '\',\'' + item.extend_data.type + '\')">' + item.extend_data.name + '</p>'
          _html += '</div></li>';
        } else {
          _html += '<div class="layim-chat-text">' + replaceContent(item.content) + '</div></li>';
        }
      }

      $('#chat-list').prepend(_html);

      setTimeout(function () {
        console.log('page', page)
        if (page == 1) {
          wordBottom();
        }
        showBigPic();
      }, 200);
    }
  });
}

function getMoreChatLog(current, uid, kf_id, page) {
  $(current).parent().remove()
  getChatLog(uid, kf_id, page)
}

// 双击图片
function showBigPic() {
  layui.use('jquery', function () {
    var $ = layui.jquery;

    $(document).on('click', '.layui-whisper-photos', function () {
      var src = this.src;
      layer.photos({
        photos: {
          data: [{
            "alt": "大图模式",
            "src": src
          }]
        }
        , shade: 0.5
        , closeBtn: 2
        , anim: 0
        , resize: false
        , success: function (layero, index) {

        }
      });
    });
  });
}

// 前往商品或优惠券详情
function gotoDetail(id, type) {
  switch (type) {
    case 'goods':
      window.location.href = config.shopSite + '/wapnew1/goods/detail/' + id
      break;
    case 'coupon':
      window.location.href = config.shopSite + '/wapnew1/coupon/detail?type=1&id=' + id
      break
    case 'coupon_pack':
      window.location.href = cosnfig.shopSite + '/wapnew1/coupon/detail?type=2&id=' + id
      break
  }
}

function cancelBubble(e) {
  var evt = e ? e : window.event;
  if (evt.stopPropagation) {        //W3C
    evt.stopPropagation();
  } else {       //IE
    evt.cancelBubble = true;
  }
}
